package nayasis.common.executor;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import nayasis.common.Const;
import nayasis.common.log.NLogger;

public class ProcessOutputThread extends Thread {

	private InputStream  inputStream;
	private StringBuffer message;

	/**
	 * 생성자
	 *
	 * @param inputStream Process 에서 출력될 메세지 Stream 객체
	 * @param message 메세지를 저장할 공간
	 */
	public ProcessOutputThread( InputStream inputStream, StringBuffer message ) {

		this.inputStream = inputStream;
		this.message = message;

	}

	/* (non-Javadoc)
	 * @see java.lang.Thread#run()
	 */
	public void run() {

		try {

			message.append( getStreamString(inputStream) );

		} catch ( Exception e ) {
			NLogger.err.println( e );

		} finally {
			try { if (inputStream != null) inputStream.close(); } catch (IOException e) {}
		}
	}

	/**
	 * 입력되는 문자열 Stream 을 문자로 변경해 돌려준다.
	 *
	 * @param inputStream 문자열 Stream
	 * @return 문자
	 */
	private String getStreamString( InputStream inputStream ) {

		StringBuffer out    = new StringBuffer();
		String       buffer = null;

		try (
			BufferedReader reader = new BufferedReader( new InputStreamReader(inputStream, Const.platform.osCharset) );
		){

			while ( (buffer = reader.readLine()) != null ) {
				out.append( buffer ).append( '\n' );
			}

		} catch ( IOException e ) {
			
			NLogger.err.println( e );

		}			
		
		return out.toString();

	}
	
}
